import java.util.*;
import java.rmi.RemoteException;
import java.rmi.NotBoundException;
import java.rmi.registry.*;
import java.sql.Time;

/** client with functionality as interpreted from assignment specifications.
 *  By Joseph Macaranas and Travis Turner
 */
public class client {

	private static final int ERROR = -1;
	private static final int RMI_PORT = 12999;
	
	private int k;
	private int t1;
	private int s1;
	private int t2;
	private int s2;
	private String server;
	
	public client(int k, int t1, int s1, int t2, int s2, String server) {
		this.k = k;
		this.t1 = t1;
		this.s1 = s1;
		this.t2 = t2;
		this.s2 = s2;
		this.server = server;
		runClient();
	}
	
	private void runClient() {
		try {
			//Lookup ref for SimpleService
			Registry registry = LocateRegistry.getRegistry(server, RMI_PORT);
			ServerInterface ref = (ServerInterface) registry.lookup("ServerInterface");
        
			long startTime = (new Date()).getTime(); 
			ServiceReply from_server_obj1 = ref.SimpleService(t1, s1); 
			long midTime = (new Date()).getTime(); 
			FinalReply client_obj = from_server_obj1.PostProcess(k * t2, s2); 
			long endTime = (new Date()).getTime(); 
			//Print out execution times, etc. 
			System.out.println("Start time: " + startTime + " ms.");
			System.out.println("Middle time: " + midTime + " ms.");
			System.out.println("End time: " + endTime + " ms.");
			System.out.println("Object reference return's approximate time: " + (endTime - midTime) + " ms.");
			System.out.println("Object return's approximate time: " + (midTime - startTime) + " ms.");
			System.out.println("This time is subject to latency delays due to network traffic.");
		} catch (RemoteException re) {
			re.printStackTrace();
		} catch (NotBoundException nbe) {
			nbe.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String [] args) {
		if (args.length != 5 && args.length != 6) {
			System.err.println("Invalid number of arguments.\nProper usage: java client k t1 s1 t2 s2 [server_hostname]");
			System.exit(ERROR);
		}
		int k = ERROR;
		int t1 = ERROR;
		int s1 = ERROR;
		int t2 = ERROR;
		int s2 = ERROR;
		String host = null;
		try {
			k = Integer.parseInt(args[0]);
			t1 = Integer.parseInt(args[1]);
			s1 = Integer.parseInt(args[2]);
			t2 = Integer.parseInt(args[3]);
			s2 = Integer.parseInt(args[4]);
			if (args.length == 6) {
				host = args[5];
			} else {
				host = "127.0.0.1";
			}
		} catch (Exception e) {
			System.err.println("Arguments need to be valid integers. Terminating...");
			System.exit(ERROR);
		}
		client c = new client(k, t1, s1, t2, s2, host);
	}
	
}
